package com.shaozj.auth.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.lang.Assert;import com.alibaba.fastjson.JSONObject;
import com.shaozj.core.constant.CacheConstants;
import com.shaozj.core.enums.StatusEnum;
import com.shaozj.core.exception.BizException;
import com.shaozj.core.result.ResultCode;
import com.shaozj.satoken.model.UserAuthInfo;
import com.shaozj.satoken.utils.LoginHelper;
import com.shaozj.auth.mapper.AuthMapper;
import com.shaozj.auth.model.form.PasswordLoginForm;
import com.shaozj.auth.service.IAuthStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("password" + IAuthStrategy.BEAN_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {

    private final StringRedisTemplate redisTemplate;
    private final AuthMapper authMapper;
    private final CodeGenerator codeGenerator;

    @Override
    public void login(PasswordLoginForm loginForm) {
        //校验验证码
        validateCaptcha(loginForm.getCaptchaId(), loginForm.getCaptchaCode());
        UserAuthInfo userAuthInfo = authMapper.getUserInfo(loginForm.getUsername());
        if (userAuthInfo == null) {
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        if (StatusEnum.DISABLE.equals(userAuthInfo.getStatus())) {
            throw new BizException(ResultCode.USER_ACCOUNT_LOCKED);
        }
        if (!BCrypt.checkpw(loginForm.getPassword(), userAuthInfo.getPassword())) {
            throw new BizException(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //TODO记录登录日志
        Long userId = userAuthInfo.getUserId();
            StpUtil.login(userId);
        //获取当前用户角色和权限
        List<String> roles = authMapper.getRolesByUserId(userId);
        List<String> perms = authMapper.getPermsByUserId(userId);
        userAuthInfo.setRoles(roles);
        userAuthInfo.setPerms(perms);

        log.info("=====userAuthInfo == {}=====", JSONObject.toJSONString(userAuthInfo));

        //登录成功缓存 当前登录用户信息
        LoginHelper.login(userAuthInfo, new SaLoginModel());
    }

    /**
     * 校验验证码
     * @param captchaId
     * @param captchaCode
     */
    private void validateCaptcha(String captchaId, String captchaCode) {
        String cacheCode = redisTemplate.opsForValue().get(CacheConstants.CAPTCHA_CODE_PREFIX + captchaId);
        Assert.isTrue(codeGenerator.verify(cacheCode, captchaCode), "验证码不正确");
    }
}
